<?php
declare (strict_types=1);
namespace app\middleware;

use app\common\lib\Aes;

class User
{
    /**
     * 处理请求
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        header('Access-Control-Allow-Origin:*');
        header('Content-Type:application/json; charset=utf-8');
        $param = $request->param();
        $debug = $_GET['debug'] ?? ($_COOKIE['debug'] ?? '');
        if ($debug === md5('debug_' . date('Ymd'))) {
            var_dump($param);
            exit;
        }
        $is_test = $param['_is_test'] ?? '';
        if ($is_test === md5('is_test_' . date('Ymd'))) {
            return $next($request);
        }
        $token = $request->cookie('user20220804', '');
        if (empty($token)) {
            echo '请登录';
            exit;
        }
        $token = $this->dataDecrypt($token);
        if (empty($token)) {
            echo '非法操作';
            exit;
        }
        $token_expire = env('index.token_expire', 3600);
        if (time() - $token['login_time'] > $token_expire) {
            echo '登录超时';
            exit;
        }
        $request->user_id = $token['id']; // 当前登录用户ID
        return $next($request);
    }

    /**
     * 数据AES解密
     * @author 贺强
     * @time   2021-03-23 15:58:50
     * @param string $ciphertext 要解密的串
     * @return mixed             返回解密后的数据
     */
    private function dataDecrypt($ciphertext)
    {
        $data = '';
        if (!empty($ciphertext)) {
            $data = (new Aes())->decrypt($ciphertext);
            if (!$data) {
                return false;
            }
            $param = json_decode($data, true);
            if (json_last_error() == JSON_ERROR_NONE) {
                $data = $param;
            }
        }
        return $data;
    }
}
